package com.haiyou.data.common.persister.mysql.help;

import java.util.Map;

import com.haiyou.common.entity.Entity;
import com.haiyou.data.common.persister.mysql.help.invoke.BlobHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.ByteHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.CustomHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.DatetimeHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.DecimalHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.DoubleHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.FloatHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.IntHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.LongHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.ShortHelper;
import com.haiyou.data.common.persister.mysql.help.invoke.TextHelper;
import com.haiyou.data.common.persister.mysql.meta.ColumnMeta;
import com.haiyou.data.common.persister.mysql.meta.TableMeta;

import lombok.extern.slf4j.Slf4j;



@Slf4j
public class EntityHelper {

	public static <T extends Entity<?>> T wrapped(Class<T> entityClass, Map<String, Object> map, TableMeta tableMeta) {

		T entity;
		try {
			
			entity = (T) entityClass.newInstance();
			for (ColumnMeta columnMeta : tableMeta.getColumnMetas()) {

				Object ov = map.get(columnMeta.getColumnName());

				if (ov == null) {
					continue;
				}

				if (columnMeta.isCustomize()) {
					new CustomHelper().invoke(columnMeta, ov, entity);
					continue;
				}

				String column_type = columnMeta.getColumnType().toLowerCase();

				if (column_type.startsWith("tinyint")) {

					new ByteHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("smallint")) {

					new ShortHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("int")) {

					new IntHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("bigint")) {

					new LongHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("float")) {

					new FloatHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("double")) {

					new DoubleHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("decimal")) {

					new DecimalHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.startsWith("datetime")) {

					new DatetimeHelper().invoke(columnMeta, ov, entity);

				} else if (column_type.contains("blob")) {

					new BlobHelper().invoke(columnMeta, ov, entity);

				} else {

					new TextHelper().invoke(columnMeta, ov, entity);// char/varchar/text

				}
			}
			return entity;
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}

	}
}
